class EventBus {
  constructor() {
    this.eventBus = {};
  }
  on(eventName, callback, thisArg) {
    let handlers = this.eventBus[eventName];
    if (!handlers) {
      handlers = [];
      this.eventBus[eventName] = [];
    }
    this.eventBus[eventName].push({ callback, thisArg });
  }
  emit(eventName, ...payload) {
    const handlers = this.eventBus[eventName];
    if (!handlers) return;
    handlers.forEach((item) => {
      item.callback.apply(item.thisArg, payload);
    });
  }
  off(eventName) {
    let handlers = this.eventBus[eventName];
    if (!handlers) {
      this.eventBus = [];
      return;
    }
    this.eventBus[eventName] = [];
  }
  once(eventName, callback, thisArg) {
    this.emit(eventName, callback, thisArg);
    this.off(eventName, callback);
  }
}

function debounce(fn, time = 500) {
  let timer;
  return function (...args) {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.call(this, ...args);
    }, time);
  };
}
function throttle(fn, time = 500) {
  let pre = Date.now();
  return function (...args) {
    const now = Date.now();
    if (pre + time <= now) {
      fn.call(this, ...args);
      pre = now;
    }
  };
}

export { EventBus, debounce, throttle };
